import CocosHelper from "../../TFrame/script/helper/CocosHelper";
import EventCenter from "../../TFrame/script/helper/EventCenter";
import EventNames from "../EventNames";
import ResManager from "../ResManager";
import GameLogicController from "./GameLogicController";

const { ccclass, property } = cc._decorator;

/**
 * 1、判定是否在游戏区域内点击
 * 2、是否点击到茬
 * 3、是否移动茬
 */
@ccclass
export default class GameTouchHandle extends cc.Component {
    @property(cc.Node)
    diffArea1: cc.Node = null;

    @property(cc.Node)
    diffArea2: cc.Node = null;

    @property(cc.Node)
    diffMoveNode1: cc.Node = null;
    @property(cc.Node)
    diffMoveNode2: cc.Node = null;

    //找茬图片容忍的边距
    diffClickDelta = 10;
    protected onLoad(): void {
        this.addEventListen();

        if(ResManager.autoTestLevels == true) {
            this.autoFind();
        }
    }

    protected autoFind() {
        for(let i = 0; i < 5; ++i) {
            this.scheduleOnce(()=>{
                GameLogicController.getInstance().findDifference(i, i);
            }, i * 0.2 + 0.1);
        }
    }

    protected addEventListen() {
        EventCenter.once(EventNames.DiffShowDone, () => {
            this.addTouchListen()
        }, this)

        EventCenter.once(EventNames.DiffAllFound, () => {
            this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this)
            this.node.off(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this)
            this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnd, this)
        }, this)
    }

    movedDistance = 0;
    protected addTouchListen() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this)
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this)
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this)
    }

    touchStart(e: cc.Event.EventTouch) {
        this.movedDistance = 0;
    }

    touchMove(e: cc.Event.EventTouch) {
        if (this.hitGameArea(e) > 0) {
            this.movedDistance += e.getDelta().len();
            if (this.movedDistance > 10) {
                this.moveDiffNode(e.getDelta())
            }
        }
    }

    touchEnd(e: cc.Event.EventTouch) {
        let hitGameArea = this.hitGameArea(e);
        if (hitGameArea > 0) {
            if (this.movedDistance < 10) {
                let idx = this.clickDiffIndexCal(e, hitGameArea);
                if (idx == -2) {
                    GameLogicController.getInstance().errorClick(e.getLocation(), hitGameArea);
                } else if(idx == -1) {
                    //do nothing for repeat click on found.
                }
                else {
                    GameLogicController.getInstance().findDifference(idx, hitGameArea);
                }
            }
        }
    }


    protected hitGameArea(e: cc.Event.EventTouch) {
        if (CocosHelper.isPtInNode(this.diffArea1, e.getLocation()))
            return 1;
        if (CocosHelper.isPtInNode(this.diffArea2, e.getLocation()))
            return 2;
        return 0;
    }

    /**
     * 
     * @param e 
     * @param hitGameArea 
     * @returns >= 0表示找到了正确区域  =-1表示重复点中找到了的区域，=-2表示错误区域
     */
    protected clickDiffIndexCal(e: cc.Event.EventTouch, hitGameArea) {
        let isClickAtFound = false;
        let areaNode = hitGameArea == 1 ? this.diffMoveNode1 : this.diffMoveNode2;// areas[areaI];
        for (let i = 0; i < ResManager.getDiffCount(); ++i) {
            let ptLocal = areaNode.convertToNodeSpaceAR(e.getLocation());
            // console.log(`i:${i}, ptlocal:${ptLocal.toString()}`)
            let cfg = ResManager.getDiffConfigRect(i);
            let ptDelta = ptLocal.sub(cc.v2(cfg.x, cfg.y))
            if (Math.abs(ptDelta.x) <= (cfg.width * 0.5 + this.diffClickDelta)
                && Math.abs(ptDelta.y) <= (cfg.height * 0.5 + this.diffClickDelta)) {
                    if(GameLogicController.getInstance().isDiffFound(i) == false) {
                        return i;
                    }
                    isClickAtFound = true;
                }
        }
        // }
        return isClickAtFound? -1: -2;
    }

    protected moveDiffNode(delta: cc.Vec2) {
        //1 未缩放不生效
        if (this.diffMoveNode1.scaleX == 1)
            return;
        //2 边界判断
        let newX = this.diffMoveNode1.x + delta.x;
        let bounceX = (this.diffMoveNode1.scaleX - 1) * this.diffArea1.width * 0.5
        newX = Math.min(newX, bounceX);
        newX = Math.max(newX, -bounceX)
        this.diffMoveNode1.x = newX;
        this.diffMoveNode2.x = newX;

        let newY = this.diffMoveNode1.y + delta.y;
        let bounceY = (this.diffMoveNode1.scaleX - 1) * this.diffArea1.height * 0.5
        newY = Math.min(newY, bounceY);
        newY = Math.max(newY, -bounceY)
        this.diffMoveNode1.y = newY;
        this.diffMoveNode2.y = newY;
    }
}
